import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    Data: [],
    tableData: [],
  },
  mutations: {
    GetData(state, Data) {
      var num = 1;
      var temp = [];
      [...Data].forEach((elem) => {
        var newdate;
        var date = new Date(Number(elem.create_time));
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        var h = date.getHours();
        var i = date.getMinutes();
        var s = date.getSeconds();
        if (num == 1) {
          newdate = `${y}-${m}-${d} ${h}:${i}:${s} 下午`;
          num = -1;
        } else {
          newdate = `${y}-${m}-${d} 0${h-12}:0${i}:${s} 晚上`;
        }
        elem.newdata = newdate;
        temp.push(elem);
      });
      state.tableData = [...temp];
      state.Data = [...temp];
    },
    Search(state, value) {
      state.tableData = [];
      [...state.Data].forEach((item) => {
        if (item.username.includes(value)) {
          state.tableData.push(item);
        }
      });
    },
    onedit(state, item) {
      state.tableData.forEach((elem) => {
        if (item.id == elem.id) {
          elem = item;
        }
      });
    },
    Delete(state, id) {
      state.tableData.forEach((elem, index) => {
        if (id == elem.id) {
          state.tableData.splice(index, 1);
        }
      });
    },
    AddUser(state, value) {
      var obj = {
        role_name: "超级管理员",
        username: value,
        create_time: 1486720211,
        mobile: "13923453488",
        email: "xranzhuan@163.com",
        mg_state: false,
        newdata: "1970-1-19 19:6:55 下午",
      };
      state.tableData.unshift(obj);
    },
  },
  actions: {
    GetData(context) {
      axios.get("userlist.json").then((res) => {
        context.commit("GetData", res.data.data.users);
      });
    },
    Search(context, value) {
      context.commit("Search", value);
    },
    onedit(context, item) {
      context.commit("onedit", item);
    },
    Delete(context, id) {
      context.commit("Delete", id);
    },
    AddUser(context, value) {
      context.commit("AddUser", value);
    },
  },
  modules: {},
});
